package com.splic.product.service.impl.thirdRequest;

import com.alibaba.fastjson.JSONObject;
import com.splic.common.utils.StringUtils;
import com.splic.product.cusEnum.WeekEnum;
import com.splic.product.domain.HolidayVacations;
import com.splic.product.dto.HolidayVacationsRequestDto;
import com.splic.product.mapper.HolidayVacationsMapper;
import com.splic.product.service.HolidayVacationsService;
import com.splic.product.service.ThirdRequestDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

/**
 * ==========================
 * 开发：singe
 * 创建时间：2022-02-28 22:11
 * 版本: 1.0
 * 描述：TODO
 * ==========================
 */
@Service
@Slf4j
public class HolidayVacationsRequestServiceImpl implements ThirdRequestDataService {

    private final String appId = "nmruorkioqapjgnm";
    private final String appSecret = "NzYrSStsVnc4U01hNEl1RkMvYkJFQT09";
    private final String url = "https://www.mxnzp.com/api/holiday/single/dateSearch?ignoreHoliday=false&app_id="+appId+"&app_secret=" + appSecret;

    @Autowired
    private HolidayVacationsMapper holidayVacationsMapper;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HolidayVacationsService holidayVacationsServiceImpl;

    @Override
    public HolidayVacationsRequestDto requestThirdData() {
        HolidayVacations origin = holidayVacationsMapper.getLastOne();
        LocalDate date;
        if (origin == null) {
            date = LocalDate.now().with(TemporalAdjusters.firstDayOfYear()).minusDays(1);
        } else {
            date = origin.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        }
        HolidayVacationsRequestDto dto = new HolidayVacationsRequestDto();
        HolidayVacations holidayVacations;
        for (int i = 0; i < 365; i ++) {
            System.out.println(i);
            String result = restTemplate.getForObject(url.replace("dateSearch", date.format(DateTimeFormatter.ofPattern("yyyyMMdd"))),String.class);
            if (StringUtils.isEmpty(result)) {
                log.error("获取日历数据失败");
                return null;
            }
            holidayVacations =new HolidayVacations();
            JSONObject resultObject = JSONObject.parseObject(result);
            if (resultObject != null && resultObject.getInteger("code") == 1) {
                JSONObject jsonObject = resultObject.getJSONObject("data");
                if (jsonObject == null){
                    return null;
                }

                holidayVacations.setDate(jsonObject.getDate("date"));
                holidayVacations.setType(jsonObject.getInteger("type"));
                holidayVacations.setTitle(jsonObject.getString("typeDes"));
                holidayVacations.setWeek(WeekEnum.getDesByWeekDay(jsonObject.getInteger("weekDay")));
                String solarTerms = jsonObject.getString("solarTerms");
                if (solarTerms.length() == 2) {
                    holidayVacations.setSolarTerms(solarTerms);
                }
                holidayVacations.setYellowCalendar(jsonObject.getString("lunarCalendar"));
                List<HolidayVacations> vacations = holidayVacationsServiceImpl.selectHolidayVacationsList(holidayVacations);
                if (vacations != null && vacations.size() > 0) {
                    holidayVacations.setId(vacations.get(0).getId());
                }
                holidayVacationsServiceImpl.saveOrUpdate(holidayVacations);
            } else {
                log.error("获取日历数据失败：" + resultObject.getString("msg"));
                break;
            }
            date= date.plusDays(1);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
